 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : EasyAvatar-Lib
 * Package  : net.solosky.easyavatar.api.impl
 * File     : QzoneFriendProvider.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : Oct 29, 2011
 * License  : Apache License 2.0 
 */
package net.solosky.easyavatar.api.impl;

import java.io.IOException;

import net.solosky.easyavatar.api.ApiException;
import net.solosky.easyavatar.api.Avatar;
import net.solosky.easyavatar.api.Avatar.Scale;
import net.solosky.easyavatar.api.ErrorCode;
import net.solosky.easyavatar.api.Friend;
import net.solosky.easyavatar.api.FriendList;
import net.solosky.easyavatar.api.Group;
import net.solosky.easyavatar.api.http.HttpRequest;
import net.solosky.easyavatar.api.http.HttpResponse;
import net.solosky.easyavatar.api.util.QQEncryptor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * QQ空间好友，和QQ列表上的好友一致
 *
 * @author solosky <solosky772@qq.com>
 *
 */
public class QzoneFriendProvider extends AbstractQQServiceFriendProvider{
	private static final String URL_MYFRIENDS = "http://r.cnc.qzone.qq.com/cgi-bin/tfriend/friend_mngfrd_get.cgi";
	private static final String URL_MAYKNOWNS = "http://r.cnc.qzone.qq.com/cgi-bin/potential/potentialpeople_py.cgi";
	private static final String URL_MYINFO    = "http://base.s14.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all";
	private static final String URL_AVATAR_G  = "http://qlogo1.store.qq.com/qzone/%s/%s/%s"; 

	@Override
	public void init() throws ApiException, IOException {
	}

	@Override
	public FriendList retireMyFriends(String index) throws ApiException,
			IOException {
		HttpRequest req = createHttpRequest(URL_MYFRIENDS, "GET");
		req.addGetValue("uin", getUin());
		req.addGetValue("g_tk", getGtk());
		req.addGetValue("rd", Math.random()+"");
		
		HttpResponse res = executeHttpRequest(req);
		validateResponse(res);
    	try {
			JSONObject json = new JSONObject(exactData(res.getResponseString()));
			
			FriendList friendList = new FriendList();
			friendList.setHasGroup(true);
			friendList.setHasNext(false);
			friendList.setNextIndex(null);
			
			JSONArray groups = json.getJSONArray("gpnames");
			for(int i=0; i<groups.length(); i++){
				JSONObject entry = groups.getJSONObject(i);
				Group group = new Group();
				group.setGid(entry.getString("gpid"));
				group.setName(entry.getString("gpname"));
				friendList.getGroups().add(group);
			}
			
			JSONArray friends = json.getJSONArray("items");
			for(int i=0; i<friends.length(); i++){
				JSONObject entry = friends.getJSONObject(i);
				Friend friend = new Friend();
				friend.setNick(entry.optString("name"));
				friend.setName(entry.optString("realname"));
				friend.setFid(entry.optString("uin"));
				friend.getAvatar().setUrl(entry.optString("imgbig"));
				friend.setGid(entry.optString("groupid"));
				
				friendList.getFriends().add(friend);
			}
			
			return friendList;
		} catch (JSONException e) {
			throw new ApiException(ErrorCode.INVALID_RESPONSE, e);
		}
	}

	@Override
	public FriendList retireMayKnowns(String index) throws ApiException,
			IOException {
		index = index!=null ? index : "0";
		HttpRequest req = createHttpRequest(URL_MAYKNOWNS, "GET");
		req.addGetValue("uin", getUin());
		req.addGetValue("g_tk", getGtk());
		req.addGetValue("random", Math.random()+"");
		req.addGetValue("page", index);
		req.addGetValue("mask", "3");
		req.addGetValue("num", "30");
		
		HttpResponse res = executeHttpRequest(req);
		validateResponse(res);
		try {
			FriendList friendList = new FriendList();
			friendList.setHasGroup(false);
			friendList.setHasNext(true);
			friendList.setNextIndex((Integer.parseInt(index)+1)+"");
			
			JSONObject json = new JSONObject(exactData(res.getResponseString()));
			JSONArray friends = json.getJSONArray("pengyou");
			for(int i=0; i<friends.length(); i++){
				JSONObject entry = friends.getJSONObject(i);
				Friend friend = new Friend();
				friend.setName(entry.optString("nick"));
				friend.setFid(entry.optString("uin"));
				friend.getAvatar().setUrl(entry.optString("icon"));
				friendList.getFriends().add(friend);
			}
			return friendList;
		} catch (JSONException e) {
			throw new ApiException(ErrorCode.INVALID_RESPONSE, e);
		}
		
		
	}

	@Override
	public Avatar retireFriendAvatar(Friend friend, Scale scale)
			throws ApiException, IOException {
		HttpRequest req = createHttpRequest(friend.getAvatar().getUrl(), "GET");
		HttpResponse res = executeHttpRequest(req);
		if(res.getResponseCode()==HttpResponse.HTTP_OK){
			friend.getAvatar().setData(res.getResponseData());
			return friend.getAvatar();
		}else if(res.getResponseCode()==HttpResponse.HTTP_MOVED_TEMP){
			req = createHttpRequest(res.getHeader("Location"),"GET");
			res = executeHttpRequest(req);
			validateResponse(res);
			friend.getAvatar().setData(res.getResponseData());
			return friend.getAvatar();
		}else{
			throw new ApiException(ErrorCode.INVALID_RESPONSE);
		}
		
	}

	@Override
	public Avatar retireMyAvatar(Friend friend, Scale scale)
			throws ApiException, IOException {
		return retireFriendAvatar(friend, scale);
	}

	@Override
	public Friend retireMyInfo() throws ApiException, IOException {
		HttpRequest req = createHttpRequest(URL_MYINFO, "GET");
		req.addGetValue("uin",getUin());
		req.addGetValue("vuin", getUin());
		req.addGetValue("rd", Math.random()+"");
		req.addGetValue("g_tk", getGtk());
		HttpResponse res = executeHttpRequest(req);
		validateResponse(res);
		try {
			JSONObject json = new JSONObject(exactData(res.getResponseString()));
			Friend friend = new Friend();
			friend.setFid(json.getString("uin"));
			friend.setNick(json.getString("nickname"));
			//friend.getAvatar().setUrl(json.getString("avatar")); 可能是主人已删除，自己组装一个URL
			friend.getAvatar().setUrl(String.format(URL_AVATAR_G, friend.getFid(), friend.getFid(), "100"));
			return friend;
		} catch (JSONException e) {
			throw new ApiException(ErrorCode.INVALID_RESPONSE);
		}
	}
	
	private String getGtk(){
		return QQEncryptor.gtk(getHttpClient().getCookie("skey").getValue());
	}
	
	private String exactData(String res){
		int start = res.indexOf("_Callback(")+"_Callback(".length();
		int end = res.lastIndexOf(");");
		return res.substring(start, end);
	}

	@Override
	protected String getAppId() {
		return "15000101";
	}

}
